package fan.codeGenerate.freeMarker;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;

/** 
* @author liu_fan 2017年3月31日 上午8:19:17  
*/
public class FreeMarker {
	
	public static Configuration cfg = new Configuration(Configuration.getVersion());
	
	public FreeMarker(String path){
		try {
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setDefaultEncoding("UTF-8");
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public String getTemplate(Map<String,Object> root,String templateName){
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		try {
			Template temp = cfg.getTemplate(templateName);
			Writer out = new OutputStreamWriter(byteArrayOutputStream);
			temp.process(root, out);
		} catch (TemplateNotFoundException e) {
			e.printStackTrace();
		} catch (MalformedTemplateNameException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return byteArrayOutputStream.toString();
	}
	
}
